package ${groupId}.service.security;

import java.io.Serializable;
import java.util.Collection;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.eventbus.AsyncEventBus;
import ${groupId}.service.security.dto.LoginUserInfo;

/**
 * Created by h.p on 2018/12/13.
 */
@Component
public class SessionService {

    @Autowired
    protected SessionDAO sessionDAO;

    public void forcedByRepeatLogin(Serializable sessionId,String type, String account, String ip) {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            PrincipalCollection principalCollection = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (principalCollection != null) {
                LoginUserInfo user = (LoginUserInfo) principalCollection.getPrimaryPrincipal();
                if (user != null && user.getUserName().equals(account) && !session.getId().equals(sessionId)) {
                    session.setTimeout(0);
                    break;
                }
            }
        }
    }


    public void forcedUserExit(String type,String account,String currentUserId, String currentUserName, String ip) {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            PrincipalCollection principalCollection = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (principalCollection != null) {
                LoginUserInfo user = (LoginUserInfo) principalCollection.getPrimaryPrincipal();
                if (user != null && user.getUserName().equals(account)) {
                    session.setTimeout(0);
                    break;
                }
            }
        }
    }

//    public void forcedMerchantUsers(List<MerUser> users, String currentUserId, String currentUserName) {
//        Collection<Session> sessions = sessionDAO.getActiveSessions();
//        for (Session session : sessions) {
//            PrincipalCollection principalCollection = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
//            if (principalCollection != null) {
//                LoginUserInfo user = (LoginUserInfo) principalCollection.getPrimaryPrincipal();
//                if (null != user) {
//                    for (MerUser account : users) {
//                        if (user.getUserName().equals(account.getPhone())) {
//                            session.setTimeout(0);
//                            break;
//                        }
//                    }
//                }
//            }
//        }
//    }
}
